//
//  NewListViewController.m
//  模拟-百思不得姐
//
//  Created by 谭浔明 on 16/8/9.
//  Copyright © 2016年 chunyu. All rights reserved.
//

#import "NewListViewController.h"
#import "EMClient.h"
#import "TalkMessageTableViewCell.h"
#import "SelfMessageViewController.h"
#import "SelfImageTableViewCell.h"
#import "TalkImageTableViewCell.h"
#import <AVFoundation/AVFoundation.h>
#import "VideoChatViewController.h"
#import "JXPMapViewController.h"
#import "TalkLocTableViewCell.h"
#import "SelfLocTableViewCell.h"
#import "SelfVoiceTableViewCell.h"
#import "TalkVoiceTableViewCell.h"
#import "RecordHUD.h"

#define viewHeight ((self.view.width - 50) / 5)

@interface NewListViewController ()<EMChatManagerDelegate,UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
// 输入框
@property (nonatomic, strong) UITextField *tf;
// 界面tab
@property (nonatomic, strong) UITableView *tab;
// 聊天信息数组
@property (nonatomic, strong) NSMutableArray *array;

@property (nonatomic, strong) UIButton *btn;
// 点击加号后，显示可以发送其它消息的按钮
@property (nonatomic, strong) UIView *otherMessageView;


@end

@implementation NewListViewController


- (NSMutableArray *)array
{
    if (!_array) {
        EMConversation *conver = [[EMClient sharedClient].chatManager getConversation:_str type:EMConversationTypeChat createIfNotExist:YES];
        _array = [[conver loadMoreMessagesFromId:nil limit:20 direction:EMMessageSearchDirectionUp] mutableCopy];
    }
    return _array;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = XMGVColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = self.str;
    [self createTab];
    [self createTF];
    [self createOtherMessageView];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getVoice:) name:@"endVoice" object:nil];
}

// 界面将显示的时候，显示到最下面的聊天信息
- (void)viewDidAppear:(BOOL)animated
{
    if (self.array.count != 0) {
        [self.tab scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.array.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    if (self.view.y != 0) {
        self.view.y -= 64;
        self.view.height += 64;
        self.tab.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
}

- (void)viewWillLayoutSubviews
{
    if (self.view.y != 0) {
        self.view.y -= 64;
        self.view.height += 64;
        self.tab.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
}


// 构建消息框
- (void)createTF
{
    self.tf = [[UITextField alloc] initWithFrame:CGRectMake(20, self.tab.bounds.size.height + 5, self.view.frame.size.width - 80, 45)];
    _tf.backgroundColor = [UIColor whiteColor];
    _tf.layer.cornerRadius = 5.f;
    _tf.returnKeyType = UIReturnKeySend;
    _tf.delegate = self;
    [self.view addSubview:_tf];
    // 键盘将要显示的消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    self.btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [_btn setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:(UIControlStateNormal)];
    _btn.frame = CGRectMake(_tf.x + _tf.width + 15, _tf.y + 5, 40, 40);
    [_btn addTarget:self action:@selector(AddAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_btn];
}
// 点击发送其它的消息
- (void)AddAction:(UIButton *)btn
{
    if ([self.tf isFirstResponder]) {
        [self.tf resignFirstResponder];
    }
    if (self.otherMessageView.y != self.view.height) {
        [UIView animateWithDuration:0.4 animations:^{
            self.tf.y += viewHeight;
            self.otherMessageView.y += viewHeight;
            self.tab.y += viewHeight;
            self.btn.y += viewHeight;
        }];
    } else {
        [UIView animateWithDuration:0.4 animations:^{
            self.tf.y -= viewHeight;
            self.otherMessageView.y -= viewHeight;
            self.tab.y -= viewHeight;
            self.btn.y -= viewHeight;
        }];
    }
}
// 键盘将要显示的通知
- (void)keyboardShow:(NSNotification *)note
{
    if (self.otherMessageView.y != self.view.height) {
        [UIView animateWithDuration:0.2 animations:^{
            self.tf.y += viewHeight;
            self.otherMessageView.y += viewHeight;
            self.tab.y += viewHeight;
            self.btn.y += viewHeight;
        }];
    }
    CGRect keyboardRect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect rect = self.tf.frame;
    CGRect rectTab = self.tab.frame;
    CGRect rectBtn = self.btn.frame;
    rect.origin.y -= keyboardRect.size.height;
    rectTab.size.height -= keyboardRect.size.height;
    rectBtn.origin.y -= keyboardRect.size.height;
    [UIView animateWithDuration:0.4 animations:^{
        self.tf.frame = rect;
        self.btn.frame = rectBtn;
        self.tab.frame = rectTab;
        if (self.array.count != 0) {
            [self.tab scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.array.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
    }];
}
// 键盘消失的通知
- (void)keyboardHide:(NSNotification *)note
{
    CGRect keyboardRect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect rect = self.tf.frame;
    rect.origin.y += keyboardRect.size.height;
    CGRect rectTab = self.tab.frame;
    rectTab.size.height += keyboardRect.size.height;
    [UIView animateWithDuration:0.4 animations:^{
        self.tf.frame = rect;
        self.btn.y += keyboardRect.size.height;
        self.tab.frame = rectTab;
        if (self.array.count != 0) {
            [self.tab scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.array.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
    }];
}
// 点击发送
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length != 0) {
        EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:self.tf.text];
        NSString *from = [[EMClient sharedClient] currentUsername];
        EMMessage *message = [[EMMessage alloc] initWithConversationID:nil from:from to:_str body:body ext:nil];
        message.chatType = EMChatTypeChat;
        [[EMClient sharedClient].chatManager asyncSendMessage:message progress:nil completion:^(EMMessage *aMessage, EMError *aError) {
            if (aError) {
                NSLog(@"%@", aError.errorDescription);
            }
        }];
        [self.array addObject:message];
        [self changeTab];
        self.tf.text = nil;
    }
    return YES;
}
// 发送消息后，要重新加载页面
- (void)changeTab
{
    [self.tab reloadData];
    [self.tab scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.array.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
// 接受对方消息的时候
- (void)didReceiveMessages:(NSArray *)aMessages
{
    for (EMMessage *message in aMessages) {
        [self.array addObject:message];
        [self changeTab];
    }
}
// 构建界面的tableview
- (void)createTab
{
    self.tab = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    self.tab.height -= 56;
    [_tab registerNib:[UINib nibWithNibName:@"TalkMessageTableViewCell" bundle:nil] forCellReuseIdentifier:@"talkCell"];
    [_tab registerNib:[UINib nibWithNibName:@"SelfMessageViewController" bundle:nil] forCellReuseIdentifier:@"selfCell"];
    [_tab registerNib:[UINib nibWithNibName:@"SelfImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"selfImageCell"];
    [_tab registerNib:[UINib nibWithNibName:@"TalkImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"talkImageCell"];
    [_tab registerNib:[UINib nibWithNibName:@"SelfLocTableViewCell" bundle:nil] forCellReuseIdentifier:@"selfLocCell"];
    [_tab registerNib:[UINib nibWithNibName:@"TalkLocTableViewCell" bundle:nil] forCellReuseIdentifier:@"talkLocCell"];
    [_tab registerNib:[UINib nibWithNibName:@"SelfVoiceTableViewCell" bundle:nil] forCellReuseIdentifier:@"selfVoiceCell"];
    [_tab registerNib:[UINib nibWithNibName:@"TalkVoiceTableViewCell" bundle:nil] forCellReuseIdentifier:@"talkVoiceCell"];
    _tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tab.delegate = self;
    _tab.dataSource = self;
    _tab.rowHeight = UITableViewAutomaticDimension;
    _tab.estimatedRowHeight = 80;
    [self.view addSubview:_tab];
}

- (void)createOtherMessageView
{
    self.otherMessageView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height, self.view.width, viewHeight + 20)];
    _otherMessageView.backgroundColor = [UIColor yellowColor];
    _otherMessageView.userInteractionEnabled = YES;
    NSArray *arr = @[@"发送图片", @"下发语音", @"视频", @"位置"];
    CGFloat temp = self.view.width / 5;
    for (int i = 0; i < 4; i++) {
        if (i == 1) {
            D3RecordButton *btn = [D3RecordButton buttonWithType:(UIButtonTypeSystem)];
            btn.frame = CGRectMake(i * temp + 10, 10, viewHeight - 20, viewHeight - 20);
            [btn setBackgroundImage:[UIImage imageNamed:arr[i]] forState:(UIControlStateNormal)];
            [btn initRecord:self maxtime:20];
            [_otherMessageView addSubview:btn];
            continue;
        }
        UIButton *btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
        btn.frame = CGRectMake(i * temp + 10, 10, viewHeight - 20, viewHeight - 20);
        [btn setBackgroundImage:[UIImage imageNamed:arr[i]] forState:(UIControlStateNormal)];
        [btn addTarget:self action:@selector(imgAction:) forControlEvents:(UIControlEventTouchUpInside)];
        btn.tag = i + 10;
        [_otherMessageView addSubview:btn];
    }
    [self.view addSubview:_otherMessageView];
}

// 点击不同图片，使用不同功能
- (void)imgAction:(UIButton *)btn
{
    if (btn.tag == 10) {
        [self imagePicker];
    } else if (btn.tag == 12) {
        VideoChatViewController *chat = [[VideoChatViewController alloc] init];
        chat.userName = _str;
        [self presentViewController:chat animated:NO completion:nil];
    } else {
        [self getLoc];
    }
}

// 位置消息
- (void)getLoc
{
    JXPMapViewController *map = [[JXPMapViewController alloc] init];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:map];
    map.type = 1;
    map.sendLoc = ^ (CLLocationCoordinate2D myLoc) {
        EMLocationMessageBody *body = [[EMLocationMessageBody alloc] initWithLatitude:myLoc.latitude longitude:myLoc.longitude address:@"我的位置"];
        // 生成message
        EMMessage *message = [[EMMessage alloc] initWithConversationID:nil from:[[EMClient sharedClient] currentUsername] to:_str body:body ext:nil];
        message.chatType = EMChatTypeChat;
        [self setMessageToServerWithMessage:message];
    };
    [self presentViewController:nc animated:YES completion:nil];
}

- (void)getVoice:(NSNotification *)ation
{
    NSString *voicePath = ation.object;
    EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithLocalPath:voicePath displayName:@"语音"];
    NSString *from = [[EMClient sharedClient] currentUsername];
    // 生成message
    EMMessage *message = [[EMMessage alloc] initWithConversationID:nil from:from to:_str body:body ext:nil];
    message.chatType = EMChatTypeChat;
    [self setMessageToServerWithMessage:message];
}


// 开始录音
-(void)dragExit{
    [_btn setTitle:@"按住录音" forState:UIControlStateNormal];
}

-(void)dragEnter{
    [_btn setTitle:@"松开发送" forState:UIControlStateNormal];
}

// 调用相册
- (void)imagePicker
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

//图片代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSData *data = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage]);
    [picker dismissViewControllerAnimated:YES completion:nil];
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:data displayName:@"image.png"];
    NSString *from = [[EMClient sharedClient] currentUsername];
    //生成Message
    EMMessage *message = [[EMMessage alloc] initWithConversationID:nil from:from to:_str body:body ext:nil];
    message.chatType = EMChatTypeChat;
    [self setMessageToServerWithMessage:message];
}

- (void)setMessageToServerWithMessage:(EMMessage *)message
{
    [[EMClient sharedClient].chatManager asyncSendMessage:message progress:nil completion:^(EMMessage *aMessage, EMError *aError) {
        if (aError) {
            NSLog(@"%@", aError.errorDescription);
        }
        [self.array addObject:aMessage];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self changeTab];
        });
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EMMessage *message = self.array[indexPath.row];
    EMMessageBody *body = message.body;
    switch (body.type) {
        case EMMessageBodyTypeText:
        {
            EMTextMessageBody *text = (EMTextMessageBody *)message.body;
            if ([message.from isEqualToString:_str]) {
                TalkMessageTableViewCell *talk = [tableView dequeueReusableCellWithIdentifier:@"talkCell" forIndexPath:indexPath];
                talk.message.text = text.text;
                return talk;
            } else {
                SelfMessageViewController *se = [tableView dequeueReusableCellWithIdentifier:@"selfCell" forIndexPath:indexPath];
                se.message.text = text.text;
                return se;
            }
        }
        case EMMessageBodyTypeImage:
        {
            EMImageMessageBody *image = (EMImageMessageBody *)message.body;
            if ([message.from isEqualToString:_str]) {
                TalkMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"talkImageCell" forIndexPath:indexPath];
                [cell.imgV sd_setImageWithURL:[NSURL URLWithString:image.thumbnailRemotePath]];
                return cell;
            } else {
                SelfImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selfImageCell" forIndexPath:indexPath];
                [cell.imgV sd_setImageWithURL:[NSURL URLWithString:image.thumbnailRemotePath] placeholderImage:[UIImage imageNamed:@"发送图片"]];
                return cell;
            }
        }
        case EMMessageBodyTypeLocation:
        {
            EMLocationMessageBody *loc = (EMLocationMessageBody *)message.body;
            if ([message.from isEqualToString:_str]) {
                TalkLocTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"talkLocCell" forIndexPath:indexPath];
                CLLocationCoordinate2D locMessage = {loc.latitude, loc.longitude};
                cell.myLoc = locMessage;
                cell.pushView = ^(CLLocationCoordinate2D myLoc) {
                    JXPMapViewController *map = [[JXPMapViewController alloc] init];
                    map.myFriendLoc = myLoc;
                    [self.navigationController pushViewController:map animated:YES];
                };
                return cell;
            } else {
                SelfLocTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selfLocCell" forIndexPath:indexPath];
                CLLocationCoordinate2D locMessage = {loc.latitude, loc.longitude};
                cell.myLoc = locMessage;
                cell.pushView = ^(CLLocationCoordinate2D myLoc) {
                    JXPMapViewController *map = [[JXPMapViewController alloc] init];
                    map.myLoc = myLoc;
                    [self.navigationController pushViewController:map animated:YES];
                };
                return cell;
            }

        }
            break;
        case EMMessageBodyTypeVoice:
        {
            EMVoiceMessageBody *voice = (EMVoiceMessageBody *)message.body;
            if ([message.from isEqualToString:_str]) {
                TalkVoiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"talkVoiceCell" forIndexPath:indexPath];
                [cell getVoiceWithVoicePath:voice.remotePath];
                return cell;
            } else {
                SelfVoiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selfVoiceCell" forIndexPath:indexPath];
                [cell getVoiceWithVoicePath:voice.remotePath];
                return cell;
            }
        }
            break;
        default:
            break;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tf resignFirstResponder];
}




@end
